<template>
  <div>
    <el-radio-group v-model="form.type" @change="radioChange">
      <el-radio label="agent">{{$t('monitor.filterByAgent')}}</el-radio>
      <el-radio label="dept" v-if="ecommerceFlag !== 'ecommerce'">{{$t('monitor.filterByDept')}}</el-radio>
      <el-radio label="queue">{{$t('monitor.filterByQueue')}}</el-radio>
    </el-radio-group>
    <div class="all-select">
      <el-select
        size="mini"
        v-if="form.type==='agent'"
        style="width: 220px;"
        v-model="selectAgents"
        collapse-tags
        :placeholder="$t('public.pleasePick')"
        @change="selectChange" filterable
        :multiple="true"
        clearable>
        <el-option
          v-for="(item, index) in allAgent"
          :label="item.displayName + '['+ item.exten + ']'"
          :key="index"
          :value="item._id">
        </el-option>
      </el-select>
      <!--多选树形组件-->
      <mulit-tree
        v-show="form.type === 'dept'"
        v-if="loaded.dept"
        key="deptAgent"
        ref="dept"
        :tree-data="deptAgent"
        @change="searchTree"
    ></mulit-tree>
      <mulit-tree
        v-show="form.type === 'queue'"
        v-if="loaded.queue"
        key="queueAgent"
        ref="queue"
        @change="searchTree"
        :tree-data="queueAgent"
      ></mulit-tree>
      <el-checkbox v-if="form.type==='agent'" v-model="form.includeSubordinate" @change="searchCheckbox" class="margin-l">{{$t('public.includeSubordinate')}}</el-checkbox>
    </div>
  </div>
</template>
<script>
  import mulitTree from '../../../ui-modules/form/mulitTree'
  // import {deepClone} from '@/utils/m7Utils'
  import {uniq} from 'lodash'
  export default {
    name: 'agentSearch',
    data () {
      return {
        ecommerceFlag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
        form: {
          type: 'agent', // 晒先类型
          branch: [], // 部门或技能组
          leaf: [], // 坐席
          includeSubordinate: false
        },
        // 按需加载，radio变化时在加载对应树
        loaded: {
          dept: false,
          queue: false
        },
        deptAgent: [], // 部门树
        queueAgent: [], // 技能组树
        allAgent: [], // 坐席数组
        selectAgents: [],
        scope: [] // 坐席权限
      }
    },
    components: {
      mulitTree
    },
    props: {
      // call or chat
      module: String,
      // 数据权限
      power: {
        type: String,
        default: 'all'
      },
      // 是否是通话座席日志组件
      isMonitorCallLog: {
        type: Boolean,
        default: false
      },
      // 停用坐席是否展示
      disableShow: {
        type: Boolean,
        default: false
      }
    },
    methods: {
      resetForm () {
        this.form = {
          type: 'agent',
          branch: [],
          leaf: [],
          includeSubordinate: false
        }
      },
      // 筛选类型变化，获取数据
      radioChange (value) {
        this.form.type = value
        this.selectAgents = []
        this.form.includeSubordinate = false
        // 切换筛选类型，emit全部
        if (value === 'agent') {
          this.selectChange([])
        } else {
          let ref = this.$refs[value]
          ref && ref.save(null, {checkedKeys: []})
        }
      },
      // 按坐席搜索change事件
      selectChange (leaf) {
        this.form.branch = []
        this.form.leaf = leaf
        if (!this.form.leaf.length) {
          // 全选
          this.form.leaf = this.allAgent.map(item => item._id)
        }
        this.$emit('change', this.form)
      },
      // 按部门或技能组搜索change事件
      searchTree ({branch, leaf}) {
        this.form.branch = branch
        this.form.leaf = this.form.type === 'queue' ? uniq(leaf.map(item => item.split(':')[0])) : leaf
        this.$emit('change', this.form)
      },
      // 我和我的下属change事件
      searchCheckbox () {
        this.$emit('change', this.form)
      },
      // 计算部门里坐席数量
      setDeptAgentCount (obj) {
        if (!obj.children && obj.type === 'agent') {
          return 1
        }

        let count = 0
        for (let i = 0; i < obj.children.length; i++) {
          count += this.setDeptAgentCount(obj.children[i])
        }
        obj.count = count
        obj.label = `${obj.label} (${count})`
        return count
      },
      powerAgent (agents) {
        return (agents || []).filter((item) => {
          if (this.power === 'call' && this.$store.state.session.user.pbx !== item.pbx && !this.isMonitorCallLog) {
            // 不是当前pbx，并且不是通话座席日志组件，直接返回fasle
            return false
          }
          return (this.disableShow || item.status === 'enable') && this.scope.indexOf(item._id) !== -1
        })
      },
      // 生成技能组树
      dealQueue (queues, arr) {
        console.log(queues)
        console.log(arr)
        let agents = this.$agentsMap()
        let child = arr[0].children
        let n = 0
        let index = 0
        for (let i = 0; i < queues.length; i++) {
          let one = queues[i]
          let obj = {
            _id: one._id,
            type: 'dept',
            label: one.DisplayName,
            children: []
          }
          if (this.module === 'business') {
            let member = one.Members || []
            member.forEach((item) => {
              if (this.scope.indexOf(item.id) !== -1) {
                let agent = agents[item.id]
                if (this.disableShow || agent.status === 'enable') {
                  obj.children.push({_id: agent._id + ':' + index++, count: 0, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin})
                  return
                }
              }
            })
          } else {
            let member = one.AssignMembers || []
            member.forEach((item) => {
              if (this.scope.indexOf(item.agentID) !== -1) {
                let agent = agents[item.agentID]
                if (this.disableShow || agent.status === 'enable') {
                  obj.children.push({_id: agent._id + ':' + index++, count: 0, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin})
                  return
                }
              }
            })
          }
          obj.label = obj.label + `(${obj.children.length})`
          n += obj.children.length
          child.push(obj)
        }
        arr[0].label = arr[0].label + `(${n})`
      },
      // 生成该坐席权限内查看的坐席
      scopeAgents (type) {
        let session = this.$store.state.session
        if (session.user.type !== 'admin' && type !== 'all' && session.user.scope[type] !== 'all') {
          let lowUsers = session.user.moduleUsers[type] || []
          return lowUsers
        } else {
          return Object.keys(this.$agentsMap())
        }
      },
      dept () {
        Promise.all([
          this.$store.dispatch('getCache', { type: 'depts' }),
          this.$store.dispatch('getCache', { type: 'agents' })
        ]).then(([depts, agents]) => {
          let optionData = []
          // 生成部门树
          let powerAgent = this.powerAgent(agents)
          dealDept(depts, optionData, '')
          // 添加坐席
          dealAgent(powerAgent, optionData[0].children)
          let noDeptAgents = powerAgent.filter(agent => !agent.deptId).map(agent => ({ _id: agent._id, count: 0, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin }))
          // 未分配部门插入到最好
          optionData[0].children.push({
            _id: 'unDept',
            type: 'dept',
            label: '未分配部门',
            order: 0,
            children: noDeptAgents
          })
          // 添加部门的坐席数
          this.setDeptAgentCount(optionData[0])
          console.log(optionData)
          this.deptAgent = optionData
          this.loaded.dept = true
        })
      },
      // 生成技能组数
      queue () {
        let action = 'queues'
        if (this.module === 'chat') {
          action = 'mailQueues'
        } else if (this.module === 'business') {
          action = 'businessQueue'
        }
        let p1 = this.$store.dispatch('getCache', {type: action})
        let p2 = this.$store.dispatch('getCache', {type: 'agents'})
        Promise.all([p1, p2]).then(([queues, agents]) => {
          // 通话筛选出当前pbx下坐席
          // 通话座席日志，按技能组筛选，需要返回所有pbx的数据，因此加上isMonitorCallLog判断
          let showQueue = queues
          if (this.power === 'call' && !this.isMonitorCallLog) {
            let pbx = this.$store.state.session.user.pbx
            showQueue = queues.filter(item => item.PBX === pbx)
          }
          let obj = {
            _id: 'all',
            type: 'dept',
            label: this.$t('public.all'),
            children: []
          }
          this.queueAgent.push(obj)
          this.dealQueue(showQueue, this.queueAgent)
          this.loaded.queue = true
        })
      },
      // 生成坐席select
      agent () {
        Promise.all([
          this.$store.dispatch('getCache', { type: 'agents' })
        ]).then(([agents]) => {
          this.allAgent = this.powerAgent(agents)
          this.radioChange('agent')
        })
      }
    },
    beforeMount () {
      this.scope = this.scopeAgents(this.power)
      // 初始化筛选
      this.agent()
      this.dept()
      this.queue()
    }
  }
  function dealDept (depts, arr, key) {
    for (let i = 0; i < depts.length; i++) {
      let dept = depts[i]
      if (dept.pId === key) {
        // 如果pid不存在为根元素，特殊标识下
        let obj = {
          _id: dept.pId ? dept._id : 'all',
          type: 'dept',
          label: dept.name,
          order: dept.order,
          children: []
        }
        arr.push(obj)
        dealDept(depts, obj.children, dept._id)
      }
    }
  }
  function dealAgent (agents, arr) {
    if (!arr) {
      return
    }
    for (let i = 0; i < arr.length; i++) {
      dealAgent(agents, arr[i].children)
      let deptAgents = agents.filter(agent => agent.deptId === arr[i]._id)
      deptAgents = deptAgents.map(agent => ({ _id: agent._id, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin }))
      arr[i].children.push(...deptAgents)
    }
  }
</script>

<style scoped lang="stylus">
  .all-select
    display inline-block
    padding-left 20px
  .margin-l
    margin-left 20px
</style>
